package com.hitcoder.chat.ui.activity

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.GridView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.effective.android.panel.PanelSwitchHelper
import com.effective.android.panel.interfaces.ContentScrollMeasurer
import com.effective.android.panel.interfaces.listener.OnPanelChangeListener
import com.effective.android.panel.interfaces.listener.OnViewClickListener
import com.effective.android.panel.view.panel.IPanelView
import com.effective.android.panel.view.panel.PanelView
import com.hitcoder.chat.R
import com.hitcoder.chat.adapter.*
import com.hitcoder.chat.databinding.ActivityChatBinding
import com.hitcoder.chat.emoji.EmotionPagerView
import com.hitcoder.chat.emoji.Emotions
import com.hitcoder.chat.model.AppBean
import com.hitcoder.chat.ui.viewmodel.ChatViewModel
import com.hitcoder.chat.ui.widget.AudioRecorderButton
import com.hitcoder.chat.utils.dip2px
import com.hitcoder.chat.utils.mAppBeanList
import com.hitcoder.chat.utils.toast
import com.rd.PageIndicatorView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.internal.notifyAll
import java.io.File

class ChatActivity : AppCompatActivity(), CoroutineScope by MainScope() {

    private var helper: PanelSwitchHelper? = null
    private var binding: ActivityChatBinding? = null
    private var viewModel: ChatViewModel? = null
    override fun onStart() {
        super.onStart()
        if (helper == null) {
            helper = PanelSwitchHelper.Builder(this)
                .addViewClickListener(object : OnViewClickListener {
                    override fun onClickBefore(view: View?) {
                        when (view?.id) {
                            R.id.edit_text,
                            R.id.add_btn,
                            R.id.voice_btn,
                            R.id.emotion_btn -> {
                                scrollToBottom()
                            }
                        }
                    }
                })
                .addPanelChangeListener(object : OnPanelChangeListener {
                    /**
                     * 唤起系统输入法
                     */
                    override fun onKeyboard() {
                        binding?.emotionBtn?.isSelected = false
                        binding?.voiceBtn?.isSelected = false
                        scrollToBottom()
                    }

                    /**
                     * 隐藏所有面板
                     */
                    override fun onNone() {
                        binding?.emotionBtn?.isSelected = false
                    }

                    /**
                     * 唤起面板
                     */
                    override fun onPanel(panel: IPanelView?) {
                        if (panel is PanelView) {
                            binding?.run {
                                emotionBtn.isSelected = panel.id == R.id.panel_emotion
                                if (voiceBtn.isSelected) {
                                    changeVoiceBtn(true, voiceBtn)
                                }
                            }

                            scrollToBottom()
                        }
                    }

                    override fun onPanelSizeChange(
                        panel: IPanelView?,
                        portrait: Boolean,
                        oldWidth: Int,
                        oldHeight: Int,
                        width: Int,
                        height: Int
                    ) {
                        if (panel is PanelView) {
                            when (panel.id) {
                                R.id.panel_emotion -> {
                                    binding?.apply {
                                        val pagerView: EmotionPagerView =
                                            root.findViewById(R.id.view_pager)
                                        val viewPagerSize: Int =
                                            height - 30f.dip2px(this@ChatActivity)
                                        pagerView.buildEmotionViews(
                                            root.findViewById(R.id.pageIndicatorView) as PageIndicatorView,
                                            editText,
                                            Emotions.emotions, width, viewPagerSize,
                                            true
                                        )
                                    }
                                }
                                R.id.panel_addition -> {
                                    binding?.apply {
                                        val gridView: GridView = root.findViewById(R.id.gv_function)
                                        gridView.adapter = ChatFunAdapter(
                                            this@ChatActivity,
                                            mAppBeanList
                                        )
                                        gridView.setOnItemClickListener { parent, _, position, _ ->
                                            val item = parent.adapter.getItem(position) as? AppBean
                                            Toast.makeText(
                                                this@ChatActivity,
                                                item?.funcName,
                                                Toast.LENGTH_SHORT
                                            ).show()
                                        }
                                    }
                                }
                            }
                        }
                    }
                })
                .addContentScrollMeasurer(object : ContentScrollMeasurer {
                    override fun getScrollDistance(defaultDistance: Int): Int {
                        return defaultDistance - unfilledHeight
                    }

                    override fun getScrollViewId(): Int {
                        return R.id.recycler_view
                    }
                })
                //设置不跟随滑动，固定在页面上
                .addContentScrollMeasurer {
                    getScrollViewId {
                        R.id.scroll_top
                    }
                }
                .addContentScrollMeasurer {
                    getScrollViewId {
                        R.id.scroll_at
                    }
                }
                .build()
            binding?.recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    val layoutManager = recyclerView.layoutManager
                    if (layoutManager is LinearLayoutManager) {
                        val childCount = recyclerView.childCount
                        if (childCount > 0) {
                            val lastChildView = recyclerView.getChildAt(childCount - 1)
                            val bottom = lastChildView.bottom
                            val listHeight: Int =
                                binding?.recyclerView?.height
                                    ?: 0 - (binding?.recyclerView?.paddingBottom ?: 0)
                            unfilledHeight = listHeight - bottom
                        }
                    }
                }
            })
        }
    }

    private var unfilledHeight = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_chat)

//        viewModel =
//            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
//                .create(ChatViewModel::class.java)
//        viewModel =
//            ViewModelProvider(
//                this,
//                ChatViewModelFactory(application, "哈哈哈")
//            ).get(ChatViewModel::class.java)

        binding?.data = viewModel
        binding?.lifecycleOwner = this

        binding?.run {
            voiceBtn.setOnClickListener {
                if (it.isSelected) {
                    helper?.toKeyboardState(true)
                }
                changeVoiceBtn(it.isSelected, it)
            }

            editText.addTextChangedListener(
                onTextChanged = { _, _, _, _ ->

                }, afterTextChanged = { changeSendBtn(it.isNullOrEmpty()) })

            send.setOnClickListener {
                editText.text?.clear()
            }
            //初始化声音文件保存位置
            voice.init(getExternalFilesDir(null)?.absolutePath ?: "")
            voice.setFinishRecorderCallBack(object :
                AudioRecorderButton.AudioFinishRecorderCallBack {
                override fun onFinish(seconds: Float, filePath: String) {
                    //录音
                    val file = File(filePath)
                    if (file.exists()) {
                    } else {
                        Toast.makeText(this@ChatActivity, "语音录制失败，请检查录音权限。", Toast.LENGTH_SHORT)
                            .show()
                    }

                }

                override fun onStart() {
                    Log.e("YQH", "开始录音")
                }

                override fun onCancel() {
                    Log.e("YQH", "取消录音")
                }
            })

            scrollTop.text =
                String.format(getString(R.string.new_msg), 11, getString(R.string.scroll_up))
            scrollAt.text =
                String.format(getString(R.string.at_msg), "张三")
            scrollBottom.text =
                String.format(getString(R.string.new_msg), 11, getString(R.string.scroll_down))

            val dataSource = initData()
            var adapter: EfficientAdapter<NumberInfo>? = null

            recyclerView.setup<NumberInfo> {
                adapter {
                    addItem(R.layout.item) {
                        bindViewHolder { data, _, _ ->
                            setText(R.id.tv_name, data?.number?.toString())
                        }
                    }
                }
                adapter = this.adapter
            }.submitList(dataSource)

            refresh.setOnRefreshListener {
                launch {
                    toast("开始刷新")
                    delay(1000)
                    dataSource.clear()
                    dataSource.addAll(initData())
                    recyclerView.adapter?.notifyDataSetChanged()
                    refresh.isRefreshing = false
                }
            }


            refresh.setOnLoadMoreListener {
                toast("下拉加载更多了")
                launch {
                    delay(1000)
                    dataSource.addAll(initData())
                    recyclerView.adapter?.notifyDataSetChanged()
                    refresh.loadMoreComplete()
                }
            }
        }


    }

    private fun initData(): ArrayList<NumberInfo> {
        val dataSource = arrayListOf<NumberInfo>()
        repeat(10) {
            dataSource.add(NumberInfo(it))
        }
        return dataSource
    }


    private fun scrollToBottom() {

    }

    private fun changeSendBtn(gone: Boolean) {
        binding?.apply {
            if (gone) {
                send.visibility = View.GONE
                addBtn.visibility = View.VISIBLE
            } else {
                send.visibility = View.VISIBLE
                addBtn.visibility = View.GONE
            }
        }
    }

    private fun changeVoiceBtn(gone: Boolean, view: View) {
        binding?.apply {
            if (gone) {
                //切换为输入状态
                voice.visibility = View.GONE
                editText.visibility = View.VISIBLE

                if (!editText.text.isNullOrEmpty()) {
                    changeSendBtn(false)
                }
            } else {
                //切换为语音状态
                voice.visibility = View.VISIBLE
                editText.visibility = View.GONE
                changeSendBtn(true)
                helper?.resetState()
            }
        }

        view.isSelected = !view.isSelected
    }

    override fun onBackPressed() {
        if (helper?.hookSystemBackByPanelSwitcher() == true) return
        super.onBackPressed()
    }


}